﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using CarolLib.WinService;

namespace CarolLib.WinServiceHost
{
    public class Program : ServiceBase
    {
        #region Framework Configuration

        private static WinServiceSetting Settings = WinServiceConfiguration.GetConfig().Settings;
        private static Dictionary<string, TaskContainer<IBasicTask>> basicTasks = WinServiceConfiguration.GetConfig().BasicTasks;

        private static System.Timers.Timer timerConsole = new System.Timers.Timer();

        private static int Debug = 0;

        private static object obj = new object();

        private static string ServicePath = Application.ExecutablePath;
        private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);

        private static bool Stopped = false;
        private static Dictionary<string, bool> ThreadStatus = new Dictionary<string, bool>();

        #endregion

        public static IBasicTask BusinessObject;
        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region 应用程序入口

        static void Main(string[] args)
        {
            Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            log4net.Config.XmlConfigurator.Configure();

            //ResolveIoC();

            bool exists = ServiceControl.CheckService(Settings.ServiceRealName);

            if (args.Length == 0)
            {
                ServiceBase.Run(new ServiceBase[] { new Program() });
            }
            else
            {
                string parm = args[0].ToLower();

                switch (parm)
                {

                    case "-debug":
                    case "/debug":

                        Debug = 1;

                        if (exists)
                        {
                            ServiceControllerStatus status = ServiceControl.GetServiceControllerStatus(Settings.ServiceRealName);

                            if (status != ServiceControllerStatus.Stopped)
                            {
                                Logger.Warn(Settings.ServiceRealName + " 服务正在运行，无法进入调试状态。请先停止该服务");
                                Console.ReadLine();
                            }
                            else
                            {
                                InitilizeCompoment();
                            }
                        }
                        else
                        {
                            InitilizeCompoment();
                        }


                        break;

                    case "-install":
                    case "-setup":
                    case "/install":
                    case "/setup":

                        if (exists)
                        {
                            Logger.Warn(Settings.ServiceRealName + " 服务已经存在，如果您想升级服务，请先卸载该服务");
                            Console.ReadLine();
                        }
                        else
                        {
                            Logger.Info(ServicePath);

                            bool result = ServiceControl.InstallService(ServicePath, Settings.ServiceRealName, Settings.ServiceDisPlayName, Settings.ServiceDescription);

                            if (result)
                            {
                                Logger.Info("服务安装成功");
                                Logger.Info("正在启动服务...");

                                ServiceControl.StartService(Settings.ServiceRealName);

                                while (!(ServiceControl.GetServiceControllerStatus(Settings.ServiceRealName) == ServiceControllerStatus.Running))
                                {
                                    while (!(ServiceControl.GetServiceControllerStatus(Settings.ServiceRealName) == ServiceControllerStatus.Running))
                                    {
                                        Thread.Sleep(Settings.BreathInterval);
                                    }
                                }

                                Logger.Info("服务已经启动");
                            }
                            else
                            {
                                Logger.Warn("服务安装失败");
                            }

                            Console.ReadLine();
                        }
                        break;

                    case "-uninstall":
                    case "-remove":
                    case "/uninstall":
                    case "/remove":

                        if (!exists)
                        {
                            Logger.Warn(Settings.ServiceRealName + "服务尚未安装");
                        }
                        else
                        {
                            bool result = ServiceControl.UnInstallService(Settings.ServiceRealName);

                            if (!result)
                            {
                                Logger.Warn("服务卸载失败");
                            }
                            else
                            {
                                Logger.Info("服务卸载成功");
                            }
                        }
                        Console.ReadLine();
                        break;
                    case "-stop":
                    case "/stop":

                        if (!exists)
                        {
                            Logger.Warn(Settings.ServiceRealName + "服务尚未安装");
                        }
                        else
                        {
                            try
                            {
                                ServiceControl.StopService(Settings.ServiceRealName);
                                Logger.Warn("服务停止成功");
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("服务停止失败", ex);
                            }
                        }

                        Console.ReadLine();
                        break;
                    case "-start":
                    case "/start":

                        if (!exists)
                        {
                            Logger.Warn(Settings.ServiceRealName +"服务尚未安装"); 
                        }
                        else
                        {
                            try
                            {
                                ServiceControl.StartService(Settings.ServiceRealName);
                                Logger.Info("服务启动成功");
                            }
                            catch (Exception ex)
                            {
                                Logger.Warn("服务启动失败", ex);
                            }
                        }

                        Console.ReadLine();
                        break;
                }
            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Logger.Fatal("未处理异常",e.Exception);
        }

        static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                Logger.Fatal("未处理异常", e.ExceptionObject as Exception);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {

            }

            base.Dispose(disposing);
        }

        public Program()
        {
            base.ServiceName = Settings.ServiceRealName;
            base.AutoLog = true;
        }

        #endregion

        #region 初始化应用程序

        private static void InitilizeCompoment()
        {
            if (Debug == 1)
            {
                Console.Title = Settings.ServiceDisPlayName;
            }

            Logger.Info("程序初始化");

            InitilizeTimer();

            Logger.Info("承载任务数:" + basicTasks.Count);

            if (Settings.ThreadCount == 1)
            {
                foreach (var item in basicTasks)
                {
                    Logger.InfoFormat("{0} 线程工作启动...", item.Key);

                    item.Value.TaskThread = new Thread(new ParameterizedThreadStart(SingleThreadTask));
                    item.Value.TaskThread.Start(item.Key);
                }
                Thread.Sleep(Settings.BreathInterval);
            }

            if (Debug == 1)
            {
                if (Settings.RunOnce)
                {
                    Console.ReadLine();
                }
            }
        }

        #endregion

        #region 业务逻辑

        private static void SingleThreadTask(object param)
        {
            var TC = basicTasks[param.ToString()];

            TC.Task.Init();

            try
            {
                while (true)
                {
                    //如果处于停止服务请求下
                    if (Stopped)
                    {
                        //跳出循环
                        TC.Task.Exit();
                        break;
                    }

                    TC.Task.Execute();

                    Thread.Sleep(TC.Interval);
                }
            }
            catch (ThreadAbortException abortException)
            {
                Logger.Error("Exception Captured in " + param.ToString() + " Thread:" + Thread.CurrentThread.ThreadState.ToString() + (string)abortException.ExceptionState, abortException);
            }
        }

        private static void MutiThreadTask(object param)
        {
            int i = (int)param;

            try
            {
                while (true)
                {
                    //如果处于停止服务请求下
                    if (Stopped)
                    {
                        lock (obj)
                        {
                            ThreadStatus[i.ToString()] = true;
                        }
                        //跳出循环
                        break;
                    }

                    Thread.Sleep(Settings.MainTaskInterval);
                }
            }
            catch (ThreadAbortException abortException)
            {
                Logger.Error("Exception Captured in Thread["+i.ToString()+"]:" + Thread.CurrentThread.ThreadState.ToString() + (string)abortException.ExceptionState, abortException);
            }
        }

        #endregion

        #region 初始化服务设置

        protected override void OnStart(string[] args)
        {
            InitilizeCompoment();
        }

        protected override void OnStop()
        {
            //停止定时器
            timerConsole.Enabled = false;

            //通知线程结束循环
            Stopped = true;

            BusinessObject.Exit();

            while (!AllStop())
            {
                Thread.Sleep(Settings.MainTaskInterval);
            }
        }

        /// <summary>
        /// 判断工作线程是否已经都停止了
        /// </summary>
        /// <returns></returns>
        private static bool AllStop()
        {
            try
            {
                lock (obj)
                {
                    foreach (bool value in ThreadStatus.Values)
                    {
                        if (!value)
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                Logger.Error("服务停止失败",e);

                return false;
            }
        }

        #endregion

        #region 初始化定时器

        /// <summary>
        /// 初始化定时器
        /// </summary>
        private static void InitilizeTimer()
        {
            // 定时清理控制台
            timerConsole.Interval = Settings.ClearConsoleInterval;
            timerConsole.Enabled = true;
            timerConsole.Elapsed += new System.Timers.ElapsedEventHandler(timerConsole_Elapsed);
            timerConsole.AutoReset = true;
        }

        /// <summary>
        /// debug模式下定时清空控制台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void timerConsole_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Debug == 1)
            {
                Console.Clear();
                Logger.Info("控制台已更新，详细信息请查看日志文件");
            }
        }

        #endregion
    }
}
